"use client"

import { useState } from "react";
import { Search } from "lucide-react";
import PlayerModal from "./player-modal";
import { getPlayerByName, getRankings } from "@/lib/data";
import { getTitleByScore } from "@/lib/utils";

export default function SearchButton() {
  const [searchQuery, setSearchQuery] = useState("");
  const [isSearching, setIsSearching] = useState(false);
  const [searchPlayer, setSearchPlayer] = useState<any>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  
  // API中使用的数值段位到名称的映射
  const TIER_NAMES: Record<number, string> = {
    1: 'HT1',
    2: 'LT1',
    3: 'HT2',
    4: 'LT2',
    5: 'HT3',
    6: 'LT3',
    7: 'HT4',
    8: 'LT4',
    9: 'HT5',
    10: 'LT5'
  };
  
  // 从段位数值获取段位名称
  const getTierName = (tierValue: number | null) => {
    if (tierValue === null || tierValue === undefined) return null;
    return TIER_NAMES[tierValue] || `Tier ${tierValue}`;
  };
  
  // 处理搜索
  const handleSearch = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!searchQuery.trim()) return;
    
    try {
      setIsSearching(true);
      // 获取搜索的玩家
      const player = await getPlayerByName(searchQuery);
      if (!player) {
        throw new Error("找不到该玩家");
      }
      
      // 获取总排行榜数据以获取更完整的信息
      const overallRankings = await getRankings("overall");
      
      // 在总排行榜中查找该玩家，获取排名和完整信息
      const overallData = overallRankings.find((p: any) => 
        p.id.toString() === player.id.toString()
      );
      
      // 获取分数
      const playerScore = overallData?.score || 0;
      
      // 获取称号信息
      const titleInfo = getTitleByScore(playerScore);
      
      // 合并数据
      const playerData = {
        ...player,
        id: player.id.toString(),
        // 排名信息
        overallRank: overallData ? overallRankings.indexOf(overallData) + 1 : undefined,
        rank: overallData ? overallRankings.indexOf(overallData) + 1 : undefined,
        
        // 分数信息
        overallScore: playerScore,
        score: playerScore,
        
        // 段位数值
        swordTier: overallData?.swordTier || player.swordTier,
        crystalTier: overallData?.crystalTier || player.crystalTier,
        buhcTier: overallData?.buhcTier || player.buhcTier,
        potionTier: overallData?.potionTier || player.potionTier,
        npotTier: overallData?.npotTier || player.npotTier,
        smpTier: overallData?.smpTier || player.smpTier,
        
        // 段位名称
        swordTierName: overallData?.swordTierName || getTierName(player.swordTier),
        crystalTierName: overallData?.crystalTierName || getTierName(player.crystalTier),
        buhcTierName: overallData?.buhcTierName || getTierName(player.buhcTier),
        potionTierName: overallData?.potionTierName || getTierName(player.potionTier), 
        npotTierName: overallData?.npotTierName || getTierName(player.npotTier),
        smpTierName: overallData?.smpTierName || getTierName(player.smpTier),
        
        // 标题信息
        title: { 
          name: titleInfo.name,
          color: titleInfo.color,
          points: playerScore,
          icon: titleInfo.icon,
          description: titleInfo.description
        }
      };
      
      console.log("搜索到的玩家数据:", playerData);
      setSearchPlayer(playerData);
      setIsModalOpen(true);
    } catch (error) {
      console.error("搜索玩家失败:", error);
      alert("找不到该玩家");
    } finally {
      setIsSearching(false);
      setSearchQuery(""); // 清空搜索框
    }
  };

  return (
    <>
      <div className="relative flex-1 max-w-sm">
        <form onSubmit={handleSearch} className="relative flex items-center">
          <input
            type="text"
            placeholder="搜索玩家..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full rounded-md bg-gray-800 px-3 py-1.5 text-sm border-transparent focus:border-transparent focus:ring-0 text-white"
          />
          <button 
            type="submit" 
            className="absolute right-2 text-gray-400"
            disabled={isSearching}
          >
            <Search className="h-4 w-4" />
          </button>
        </form>
      </div>
      
      {/* 搜索结果模态窗口 */}
      {searchPlayer && (
        <PlayerModal 
          player={searchPlayer} 
          isOpen={isModalOpen} 
          onClose={() => {
            setIsModalOpen(false);
            // 稍后重置玩家数据，避免模态窗口关闭动画被打断
            setTimeout(() => setSearchPlayer(null), 300);
          }} 
        />
      )}
    </>
  );
} 